<template>
    <div class="container">
        <div class="chart-content">
            <div :id="container" class="chart-views"></div>
        </div>
    </div>
</template>
<script>
import { dateFormatter, formatterNum } from '@/common/js/util.js'
import { formatData } from '@/common/js/chartsFormat'
import Highcharts from 'highcharts';
export default {
    props: {
        dataArr: {
            type: Object,
            default: {}
        }, 
        container: {
            type: String,
            default: 'c1'
        }
    },
    data() {
        return {
            charts: null,
            particleSize: 'day',       // 粒度
        }
    },
    methods: {
        chartInit(dataArr = null) {
            const that = this;
            dataArr = JSON.parse(JSON.stringify(dataArr));
            
            dataArr.series = dataArr.series.map(item => {
                // 针对series每个图形元素单独设置填充色
                item.fillColor = {
                    linearGradient: { x1: 0, x2: 0, y1: 0, y2: 0.9 }, // 线性渐变
		    	    stops: [
		    	        [0, Highcharts.color(item.color).setOpacity(0.3).get('rgba')],
		    	        [1, Highcharts.color(item.color).setOpacity(0).get('rgba')]
		    	    ]
                }
                // 根据粒度格式数组
                item.data = formatData(item.data, this.particleSize);
                return item;
            })
            
            this.charts = Highcharts.chart(this.container, {
                chart: Object.assign({ 
                    type: 'areaspline',
                    backgroundColor: 'none', // 只能设为空背景，否则标题则不显示，因为css更改了图表、标题、提示框三者的层级(z-index)
                }, dataArr.chart), 
	            title: Object.assign({
                    text: null,
                    align: 'center',
                    useHTML: true,
                    margin: 12,
                    y: 5,
                    style: { 
                        "color": dataArr.series[0].color, 
                        "fontSize": "12px",
                        "display": 'block',
                        "backgroundColor": Highcharts.color(dataArr.series[0].color).setOpacity(0.1).get('rgba'),
                        "zIndex": 1,
                    }
                }, dataArr.title || {}),
                credits: { enabled: false },  // 去版权水印
                exporting: { enabled: false }, // 隐藏导出
                yAxis: Object.assign({
	            	title: false,
                    allowDecimals: false, // 禁止出现小数
                    minRange: 1, // 最小范围
                    min: 0, // 最小刻度值
                    labels: {
                        style: {
                            color: '#888888'
                        }
                    },
	            }, dataArr.yAxis || {}),
		        xAxis: {
                    type: that.particleSize == 'day' ? 'datetime' : 'category',
                    dateTimeLabelFormats: {
                        day: '%m-%d' // 时间格式化
                    },
                    labels: {
                        style: {
                            color: '#888888'
                        },
                        y: 22,
                        formatter: function() {
                            if(this.axis.options.type == 'datetime') {
                                return dateFormatter("MM-DD", this.value) // 标签格式化，针对缩小时日期变为英文格式
                            }
                            return this.value 
                        }
                    },
                    tickWidth: 1,
                    tickmarkPlacement: 'on',
                    tickLength: 5, // 刻度线长度
	            	crosshair: {
	            		dashStyle: 'Solid', // 十指辅助线
                        width: 1,
                        color: '#cccccc'
	            	},
                    tickPositioner: function (min, max) {
                        const interval = this.options.type == 'datetime' ? 24 * 3600 * 1000 : 1;
			        	const diff = (this.dataMax - this.dataMin) / (interval), width = this.width;
                        let n = 12;
                        if(that.particleSize == "week") {
                            n = 10;
                        }
                        let step = Math.floor(width * n / 1080); // 根据宽度自动调整 步阶(width = 1080px 可以放 10 个刻度)
                        if(step > diff) {
                            step = diff
                        }
                        var positions = [],
			        		tick = Math.floor(this.dataMin),
			        		increment = Math.ceil(diff / step) * interval; // 增量
			        	for (tick; tick - increment < this.dataMax; tick += increment) {
                            // if(tick < this.dataMax && (tick + increment) > this.dataMax) {
                            if(tick > this.dataMax) {
                                tick = this.dataMax;
                            }
			        		positions.push(tick);
			        	}
                        if(positions.length < 1) positions = [0] // 当min = max = 0的情况下，需默认给出一个初始值
			        	return positions;
			        },
		        },
                tooltip: {
                    shared: true, // 数据共享
                    borderRadius: 6,  
                    borderWidth: 0,
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    useHTML: true,
                    formatter: function(e) {
                        let html = null;
                        this.points.forEach(point => {
                            let value = point.series.xAxis.options.type == 'datetime' ? dateFormatter("MM-DD", point.x) : point.key;
                            if(!html) html = `<small style="margin-bottom:5px;display:block">${value}</small><span style="color:${point.color};font-size:14px">●</span> ${point.series.name}: ${formatterNum(point.y)}${point.series.tooltipOptions.valueSuffix}<br/>`
                            else html = html + `<span style="color:${point.color};font-size:14px">●</span> ${point.series.name}: ${formatterNum(point.y)}${point.series.tooltipOptions.valueSuffix}<br/>` 
                        })
                        
                        return html
                    },
                    padding: 12,
                },
                legend: {
                    enabled: false, // 隐藏图例
                    symbolHeight: 10,
                    labelFormatter: function(e) {
                        const total = this.yData.reduce((sum, item) => {
                            return sum + item;
                        }, 0)
                        return `${this.name}: ${total}${this.tooltipOptions.valueSuffix}`
                    },
                    symbolRadius: 0
                },
                /* 下面的是通用配置 */
	            plotOptions: {
	            	areaspline: {
	            		dashStyle: 'Solid',
	            	},
                    series: {
	            		fillOpacity: 0.2,
                        lineWidth: 2,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        marker: {
                            fillColor: '#ffffff',
                            radius: 3,
                            lineWidth: 2,
                            lineColor: null,
                            enabled: dataArr.series[0].data.length < 120 ? true : false, // 线上标记圆点, 当数据长度大于 120 则不显示标记点，否则太紧凑
                            states: {
                                hover: { // 标记(marker)悬停状态
                                    enabled: false
                                }
                            }
                        },
                        states: { // 线、面、柱状态
                            hover: { // 区域悬停状态
                                lineWidth: 2,
                                enabled: false
                            }
                        }
                    }
	            },
		        series: dataArr.series
            })

            // 批量更新 当值为 0 则不显示marker(标记点)
            if(dataArr.markerEnabled) {
                for(let key of this.charts.series.keys()) {
                    for(let [index, value] of this.charts.series[key].data.entries()) {
                        if(value.y == 0) {
                            this.charts.series[key].data[index].update({
                                marker: {
                                    enabled: false
                                }
                            })
                        }
                    }
                }
            }
        }
    },
    watch: {
        'dataArr.series': {
            handler(val, oldVal) {
                if(this.dataArr.particleSize) {
                    this.particleSize = this.dataArr.particleSize; // 更新粒度
                }
                if(val != oldVal) {
                    this.chartInit(this.dataArr);
                } else {
                    val.forEach((item, key) => {
                        this.charts.series[key].update({
                            visible:item.visible
                        })
                    })
                }
            },
            deep: true
        }
    }
}
</script>
<style lang="scss" scoped>
    .container, .chart-views {
        width: 100%;
        height: 100%;
    }
    .chart-content {
        width: 100%;
        height: 100%;
        padding: 0px;
    }
    /deep/.highcharts-halo.highcharts-color-undefined{
        fill: transparent; // 清除标记点 阴影背景
    }
    /deep/.highcharts-container {
        height: 100%!important;
        width: 100%!important;
        .highcharts-root {
            height: 100%!important;
            width: 100%!important;
        }
    }
</style>